<?php

namespace app\admin\service;

use bxkj_common\service\Sevrice;
use think\facade\Db;

class SysConfig extends Sevrice
{
    public function resetConfig($debug = false)
    {
        $result = Db::name('sys_config')->select();

        if (empty($result)) return true;

        $data = [];

        foreach ($result as $value) {
            $config = json_decode($value['value'], true);
            if (empty($config)) continue;
            if (array_key_exists($value['classified'], $data))
                $data[$value['classified']] = array_merge($data[$value['classified']], $config);
            else
                $data[$value['classified']] = $config;
        }

        foreach ($data as $key => $value) {
            $path = \think\facade\App::getRootPath() . 'config' . DIRECTORY_SEPARATOR .'pro'. DIRECTORY_SEPARATOR . $key . '.php';
            try {
                file_exists($path) && unlink($path);
                file_put_contents($path, "<?php  \r\n return " . var_export($value, true) . ";", LOCK_EX);
            } catch (\Exception $e) {
                exit($e->getMessage());
            }
        }

        return true;
    }

    public function addConfig($data)
    {
        $res = Db::name('sys_config')->insertGetId($data);
        return $res;
    }

    public function getConfig($name)
    {
        $config = Db::name('sys_config')->where(["mark" => $name])->find();
        return $config;
    }

    public function updateConfig($where, $data)
    {
        $status = Db::name('sys_config')->where($where)->update($data);
        return $status;
    }
}